package com.glory.brepda.activity.recipe;

import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.adapter.FTTestProgramListAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.EqpInfoEntity;
import com.glory.brepda.entity.FTTestProgramListEntity;
import com.glory.brepda.entity.LotInfoEntity;
import com.glory.brepda.entity.ProgramEqpInfoEntity;
import com.glory.brepda.entity.UpdateIPEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.LotUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import butterknife.BindView;
import butterknife.OnClick;

public class ProgramDownLoadActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etEqpWorkID)
    FreeUI_ClearEditText etEqpWorkID;
    @BindView(R.id.etEqpItemWorkID)
    FreeUI_ClearEditText etEqpItemWorkID;
    @BindView(R.id.tvProgramType)
    TextView tvProgramType;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.tvCircuit)
    TextView tvCircuit;
    @BindView(R.id.tvCustomCode)
    TextView tvCustomCode;
    @BindView(R.id.tvChipName)
    TextView tvChipName;
    @BindView(R.id.tvLineID)
    TextView tvLineID;
    @BindView(R.id.tvPackageType)
    TextView tvPackageType;
    @BindView(R.id.rbA)
    RadioButton rbA;
    @BindView(R.id.rbB)
    RadioButton rbB;
    @BindView(R.id.tvGetProgram)
    TextView tvGetProgram;
    @BindView(R.id.rvProgramList)
    RecyclerView rvProgramList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    private FTTestProgramListAdapter mFtTestProgramListAdapter;
    private LotInfoEntity mLotInfoEntity = new LotInfoEntity();
    private String mStationID = "";
    private String mProcessName = "";
    private String mPlantName = "";
    private String mEqpType = "";

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_program_download;
    }

    @Override
    protected void initView() {
        setMainLayout(llMain);
        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        tvBaseSubmit.setText("下载");
        initRecyclerView(rvProgramList,this);
        mFtTestProgramListAdapter = new FTTestProgramListAdapter(null);
        mFtTestProgramListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mFtTestProgramListAdapter.isFirstOnly(true);
        rvProgramList.setAdapter(mFtTestProgramListAdapter);

        initEdit(etLot, s -> LotUtils.searchLotInfo(ProgramDownLoadActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
            @Override
            public void onSuccess(LotInfoEntity response) {//LOTQUERY接口
                tvCircuit.setText(response.getPRODUCTMODEL());//电路名
                String customercode = response.getLOT().getCUSTOMERCODE();//客户号
                if (customercode.length() < 6 && customercode.length() > 0) {
                    tvCustomCode.setText("GD" + customercode);
                }else {
                    tvCustomCode.setText(customercode);
                }
                tvChipName.setText(response.getCHIPNAME());//芯片名
                tvPackageType.setText(response.getLOT().getMAINMATTYPE());//封装形式
                tvLineID.setText(response.getLINEID());//订单号
                mLotInfoEntity = response;
            }

            @Override
            public void onFail(Throwable t) {
                loadError(t, "LOTQUERY");
            }
        }));

        initEdit(etEqpItemWorkID, s -> {
            if (getText(etEqpWorkID).equals("")){
                showToast("请先扫描分选机ID",false);
                etEqpWorkID.setText("");
                return;
            }

            //请求设备类型、测试机列表
            LotUtils.searchEqpInfo(getText(etEqpWorkID), ProgramDownLoadActivity.this, getSupportFragmentManager(), new LotUtils.netCallback<EqpInfoEntity>() {
                @Override
                public void onSuccess(EqpInfoEntity response) {
                    if (response.getLISTEQUIPMENT().size() >= 0) {
                        for (EqpInfoEntity.TestEqpEntity entity : response.getLISTEQUIPMENT()){
                            if (entity.getEQUIPMENTID().equals(s)){
                                requestEqpType(s);
                                return;
                            }
                        }
                    }

                    showToast("当前测试机与分选机无绑定关系，请重新输入",false);
                    etEqpItemWorkID.setText("");
                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t,"EQPQUERY");
                }
            });
        });
    }

    @Override
    protected void initData() {

    }

    private void requestEqpType(String eqpID){
        FreeUI_EntityCallBack<BaseResponseBean<ProgramEqpInfoEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<ProgramEqpInfoEntity>>
                (new TypeToken<BaseResponseBean<ProgramEqpInfoEntity>>() {
                }.getType(), getSupportFragmentManager(), ProgramDownLoadActivity.this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<ProgramEqpInfoEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    //测试平台
                    if (!response.body().getResponse().getBody().getPROCESSNAME().equals("AE")){
                        showToast("当前页面只能下载AE工序的程序",false);
                        etEqpItemWorkID.setText("");
                        etEqpWorkID.setText("");
                        return;
                    }
                    requestEqpInfo(eqpID);
                    tvProgramType.setText(response.body().getResponse().getBody().getPROGRAM_TYPE());//测试平台 GETEQPINFOBYEQPID接口

                }


            }

            @Override
            public void onError(Response<BaseResponseBean<ProgramEqpInfoEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"GETEQPINFOBYEQPID");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("EQPID",eqpID);
        NetUtils.requestPostNet("GETEQPINFOBYEQPID","GETEQPINFOBYEQPID",ProgramDownLoadActivity.this,map,callBack);
    }

    private void requestEqpInfo(String eqpID) {
        FreeUI_EntityCallBack<BaseResponseBean<UpdateIPEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<UpdateIPEntity>>
                (new TypeToken<BaseResponseBean<UpdateIPEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<UpdateIPEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    UpdateIPEntity body = response.body().getResponse().getBody();
                    mProcessName = body.getPROCESSNAME();
                    mPlantName = body.getFAB();
                    mEqpType = body.getPROGRAM_TYPE();
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<UpdateIPEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "GETEQPINFOBYEQPID");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("EQPID",eqpID);
        NetUtils.requestPostNet("EAP.GETEQPINFOBYEQPID","GETEQPINFOBYEQPID", ProgramDownLoadActivity.this,map,callBack);
    }

    @OnClick({R.id.tvBaseSubmit,R.id.tvGetProgram,R.id.rbB,R.id.rbA})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
//                if (actionControl("DownLoad04"))
//                    return;

                if (getText(etEqpItemWorkID).equals("") || getText(etLot).equals("")) {
                    showToast("测试机设备或批次号不能为空", false);
                    return;
                }

                if (mStationID.equals("")){
                    showToast("请选择站点",false);
                    return;
                }

                if (mFtTestProgramListAdapter.getData().size() <= 0){
                    showToast("请先查询可用程序列表",false);
                    return;
                }
                submit();
                break;
            case R.id.tvGetProgram:
                if (getText(etEqpItemWorkID).equals("") || getText(etLot).equals("")) {
                    showToast("测试机设备或批次号不能为空", false);
                    return;
                }
                mFtTestProgramListAdapter.getData().clear();
                requestProgram(getText(etEqpItemWorkID));
                break;
            case R.id.rbA:
                mStationID = "StationA";
                break;
            case R.id.rbB:
                mStationID = "StationB";
                break;
        }
    }

    private void submit() {
        showSubmitDialog(new onSubmitListener() {
            @Override
            public void setOnSubmitListener() {
                FreeUI_EntityCallBack<BaseResponseBean<FTTestProgramListEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<FTTestProgramListEntity>>
                        ("正在下载程序",new TypeToken<BaseResponseBean<FTTestProgramListEntity>>() {
                        }.getType(), getSupportFragmentManager(), this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<FTTestProgramListEntity>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                            if (response.body().getResponse().getBody() == null){
                                return;
                            }
                            showConfirmDialog(ProgramDownLoadActivity.this,response.body().getResponse().getBody().getPrgLocalFile());
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<FTTestProgramListEntity>> response) {
                        super.onError(response);
                        loadError(response.getException(), "DownLoadProgram");
                    }
                };

                JsonObject map = new JsonObject();
                map.addProperty("TesterEqpID",getText(etEqpItemWorkID));
                map.addProperty("LotID",getText(etLot));
                map.addProperty("StationID",mStationID);
                map.addProperty("CUSTOMERCODE",tvCustomCode.getText().toString());
                map.addProperty("LINEID",tvLineID.getText().toString());
                map.addProperty("PrgName",mFtTestProgramListAdapter.getData().get(0).getRecipeID());
                map.addProperty("PrgFile",mFtTestProgramListAdapter.getData().get(0).getFileUrl());
                map.addProperty("SiteNo",mFtTestProgramListAdapter.getData().get(0).getSiteNo());
                map.addProperty("GradingMarker",mFtTestProgramListAdapter.getData().get(0).getGradingMark());
                NetUtils.requestPostNet("DownLoadProgram","DownLoadProgram",ProgramDownLoadActivity.this,map,callBack);
            }
        });
    }

    private void requestProgram(String eqpID) {
        FreeUI_EntityCallBack<BaseResponseBean<FTTestProgramListEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<FTTestProgramListEntity>>
                (new TypeToken<BaseResponseBean<FTTestProgramListEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<FTTestProgramListEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    FTTestProgramListEntity body = response.body().getResponse().getBody();
                    if (body.getRecipeID().equals("") || body.getFileUrl().equals("")){
                        showConfirmDialog("暂无数据");
                        return;
                    }
                    mFtTestProgramListAdapter.addData(response.body().getResponse().getBody());
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<FTTestProgramListEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "GetRecipeAvailable");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("EqpID", eqpID);
        map.addProperty("ProcessName",mProcessName);
        map.addProperty("EqpType",mEqpType);
        map.addProperty("PlantName",mPlantName);
        map.addProperty("BDID", mLotInfoEntity.getWIRINGNO());
        map.addProperty("WireType", mLotInfoEntity.getWIRESPEC());
        map.addProperty("DeviceName", mLotInfoEntity.getPRODUCTMODEL());
        map.addProperty("ChipName", mLotInfoEntity.getCHIPNAME());
        map.addProperty("LotID", getText(etLot));
        map.addProperty("LineID",tvLineID.getText().toString());
        map.addProperty("CustomerCode", tvCustomCode.getText().toString());
        NetUtils.requestPostNet("GetRecipeAvailable", "GetRecipeAvailable", ProgramDownLoadActivity.this, map, callBack);
    }

}
